<div id="editmap_container"><div id="map"></div></div>

<% content_for :page_scripts do %>
<script src="//maps.google.com/maps/api/js?v=3.8&amp;sensor=false&amp;key=&amp;libraries=geometry&amp;language=&amp;hl=&amp;region=" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
  // There are three scenarios here:
  // 1) We are given a lat/lng in the post params (user clicked on the map to add something).
  //    Which we'll know because @location will be a new object with lat/lng set and 
  //    the location_lat and location_lng fields will have stuff in them.
  // 2) We aren't given a lat/lng in the post params, but we're able to use the geolocation
  //    library to guess the user's position. We'll know this because location_lat and location_lng
  //    will be empty and geolocation will succeed.
  // 3) We aren't given a lat/lng and geolocation fails. In this case marker will be left set to null,
  //    and nothing should be placed on the map until the user enters an address or lat/lng

  // ================= globals ==================

  var marker = null;

  // ================= functions =================

  function initialize() {
    var mapOptions = {
      zoom: 1,
      center: new google.maps.LatLng(37.269174,-119.306607),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map'),mapOptions);
    geocoder = new google.maps.Geocoder();

    google.maps.event.addListener(map, 'rightclick', function(event) {
      remove_add_marker();
      place_add_marker(event.latLng);
    });

    google.maps.event.addListener(map, 'click', function(event) {
      if(openMarker != null && openInfoWindow != null){
        openInfoWindow.close();
        openMarker = null;
        openInfoWindow = null;
      }
    });

    pb = progressBar();
    map.controls[google.maps.ControlPosition.RIGHT].push(pb.getDiv());

    google.maps.event.addListener(map, 'bounds_changed', function() {
      google.maps.event.addListenerOnce(map, 'idle', function(){
        var zoom = map.getZoom();
        var bounds = map.getBounds();
        if(prior_bounds == null && prior_zoom == null){
          prior_zoom = zoom;
          prior_bounds = bounds;
          return;
        }
        if(zoom > 11 && prior_bounds != bounds){
          do_markers(bounds,null,true);
        }
        prior_zoom = zoom;
        prior_bounds = bounds;
      });
    });

    if($('location_lat').value == "" && $('location_lng').value == ""){
      navigator.geolocation.getCurrentPosition(function(position){
        // Case #2
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        $('location_lat').value = lat;
        $('location_lng').value = lon;
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(lat,lon), 
          map: map,
          draggable: true,
          icon: ''
        });
        map.setZoom(15);
        map.panTo(marker.getPosition());
        var nag = new google.maps.InfoWindow({
          content: '<div id="editmarker"><b>Please adjust the marker to<br>the position of the source.</b><br><br><i>Check the satellite view - your<br>plant may be visible from space!</i></div>'
        });
        nag.open(map,marker);  
        google.maps.event.addListener(marker, 'dragend', function() {
          $("location_lat").value = this.getPosition().lat();
          $("location_lng").value = this.getPosition().lng();
        });
        // update markers once we're done panning and zooming
        google.maps.event.addListenerOnce(map, 'idle', function(){
          do_markers(map.getBounds(),null,true);
        });
      },function(error){
        //use error.code to determine what went wrong
      });
      var watchID = navigator.geolocation.watchPosition(function(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        $('location_lat').value = lat;
        $('location_lng').value = lon;
        marker.setPosition(new google.maps.LatLng(lat,lon));
      },function(error){
        //...
      },{enableHighAccuracy:true, maximumAge:30000, timeout:30000});
    }else{
      // Case #1
      var lat = $("location_lat").value;
      var lng = $("location_lng").value;
      marker = new google.maps.Marker({
        icon: '',
        position: new google.maps.LatLng(lat,lng), 
        map: map,
        draggable: true,
      });
      map.setZoom(15);
      map.panTo(marker.getPosition());
      var nag = new google.maps.InfoWindow({
        content: '<div id="editmarker"><b>Please adjust the marker to<br>the position of the source.</b><br><br><i>Check the satellite view - your<br>plant may be visible from space!</i></div>'
      });
      nag.open(map,marker);  
      google.maps.event.addListener(marker, 'dragend', function() {
        $("location_lat").value = this.getPosition().lat();
        $("location_lng").value = this.getPosition().lng();
      });
      // update markers once we're done panning and zooming
      google.maps.event.addListenerOnce(map, 'idle', function(){
        do_markers(map.getBounds(),null,true);
      });
    }
  }

  function update_marker(){
    if($("location_address").value == "") return;
    geocoder.geocode( { 'address': $("location_address").value }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.panTo(results[0].geometry.location);
        map.setZoom(15);
        var lat = results[0].geometry.location.lat();
        var lng = results[0].geometry.location.lng();
        $("location_lat").value = lat;
        $("location_lng").value = lng;
        if(marker != null){
          marker.setMap(null);
          marker = null;
        }
        marker = new google.maps.Marker({
          icon: '',
          position: new google.maps.LatLng(lat,lng), 
          map: map,
          draggable: true,
        });
        var nag = new google.maps.InfoWindow({
          content: '<div id="editmarker"><b>Please adjust the marker to<br>the position of the source.</b><br><br><i>Check the satellite view - your<br>plant may be visible from space!</i></div>'
        });
        nag.open(map,marker);  
        google.maps.event.addListener(marker, 'dragend', function() {
          $("location_lat").value = this.getPosition().lat();
          $("location_lng").value = this.getPosition().lng();
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  // ================== main-level code ===================

  google.maps.event.addDomListener(window, 'load', initialize);

</script>
<%= javascript_include_tag "maplabel" %>
<%= javascript_include_tag "progressBar" %>
<%= javascript_include_tag "richmarker" %>
<%= javascript_include_tag "mapcommon" %>
<% end %>

<%= render 'form' %>
